﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Web;
using System.Web.Caching;
using System.IO;
using System.Collections;

namespace BaseCoder
{
    public  class ConfigReader
    {
        public  ConfigItem this[string configPath]
        {
            get
            {
                if (!File.Exists(configPath))
                    throw new Exception("项目配置文件不存在");
                string cacheKey = configPath.Replace("\\", "").Replace(":", "");
                if (HttpRuntime.Cache[cacheKey] == null)
                    return ReadConfig(configPath, cacheKey);
                return (ConfigItem)HttpRuntime.Cache[cacheKey];
            }
        }
        private static ConfigItem ReadConfig(string configPath, string cacheKey)
        {
            ConfigItem configItem = new ConfigItem();
            XElement root = XElement.Load(configPath);
            foreach (XElement element in root.Element("database").Elements("item"))
            {
                configItem.DBString.Add(element.Attribute("name").Value, element.Attribute("connectionString").Value);
            }
            configItem.FileRoot.BLLPath = root.Element("fileRoot").Element("bllPath").Value;
            configItem.FileRoot.DALPath = root.Element("fileRoot").Element("dalPath").Value;
            configItem.FileRoot.ModelPath = root.Element("fileRoot").Element("modelPath").Value;
            configItem.Namespace.BLLNamespace = root.Element("namespace").Element("bllNamespace").Value;
            configItem.Namespace.DALNamespace = root.Element("namespace").Element("dalNamespace").Value;
            configItem.Namespace.ModelNamespace = root.Element("namespace").Element("modelNamespace").Value;
            HttpRuntime.Cache.Insert(cacheKey, configItem, new CacheDependency(configPath), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            return configItem;
        }
    }

    public class ConfigItem
    {
        public Hashtable DBString;
        public FileRootCls FileRoot;
        public NamespaceCls Namespace;

        public ConfigItem()
        {
            DBString = new Hashtable();
            this.FileRoot = new FileRootCls();
            this.Namespace = new NamespaceCls();
        }
        public class FileRootCls
        {
            public string ModelPath { get; set; }
            public string DALPath { get; set; }
            public string BLLPath { get; set; }
        }
        public class NamespaceCls
        {
            public string ModelNamespace { get; set; }
            public string DALNamespace { get; set; }
            public string BLLNamespace { get; set; }
        }
    }
}
